package com.example.demo.util;

import org.springframework.web.multipart.MultipartFile;

import java.io.*;

/**
 * @author ChenXU
 * @version 1.0
 * @createTime 2020-10-29 08:38
 * @description
 */
public class FileUtil {

    /**
     * 文件上传处理
     *
     * @param file 文件信息
     * @param dir  file存放文件目录
     * @return 文件路径
     * @throws IOException
     */
    public static String uploadFile(MultipartFile file, String rootPath, String projectDir, String dir, String moduleName) {
        String fileName = FileUtil.buildFileName(file, moduleName);
        File targetFile = new File(rootPath + projectDir + dir);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        String filePath = rootPath + projectDir + dir + fileName;
        //流是对字符操作的
        BufferedInputStream inputStream=null;
        BufferedOutputStream outputStream=null;
        try {
             inputStream=new BufferedInputStream(file.getInputStream());
             outputStream= new BufferedOutputStream(new FileOutputStream(filePath));
            byte[] buffer=new byte[1024];
            int len=-1;
            while ((len=inputStream.read(buffer))!=-1){
                outputStream.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (outputStream != null) {
                    outputStream.close();
                }
                if(inputStream!=null){
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return projectDir + dir + fileName;
    }

    /**
     * 构建文件名
     *
     * @param file
     * @param moduleName
     * @return
     */
    private static String buildFileName(MultipartFile file, String moduleName) {
        String ext = file.getOriginalFilename().split("\\.")[file.getOriginalFilename().split("\\.").length - 1];
        return moduleName + System.currentTimeMillis() + RandomUtil.getRandomString(8) + "." + ext;
    }
}
